// utils/api.js - API服务模块
const config = require('./config.js');

const api = {
  baseURL: config.API_BASE_URL,
  timeout: 120000, // 120秒超时，增加到2分钟

  /**
   * 通用请求方法
   */
  request: function(options) {
    return new Promise((resolve, reject) => {
      const { url, method = 'GET', data = {}, header = {} } = options;
      
      // 获取用户token（登录等公开接口不携带token）
      const publicPaths = ['/api/user/login/wechat', '/api/user/wechat-login'];
      const isPublicRequest = publicPaths.includes(url);
      const token = wx.getStorageSync('token');
      
      // 设置默认请求头
      const defaultHeaders = {
        'Content-Type': 'application/json',
        ...header
      };
      
      // 如果有token且不是公开接口，添加Authorization头
      if (token && !isPublicRequest) {
        defaultHeaders['Authorization'] = `Bearer ${token}`;
      }
      
      const requestOptions = {
        url: this.baseURL + url,
        method: method.toUpperCase(),
        data,
        header: defaultHeaders,
        timeout: this.timeout,
        success: (res) => {
          console.log(`API请求成功: ${method.toUpperCase()} ${url}`);
          console.log('HTTP状态码:', res.statusCode);
          console.log('响应数据:', res.data);
          console.log('响应头:', res.header);
          
          // 检查HTTP状态码
          if (res.statusCode !== 200) {
            console.error(`HTTP错误: ${res.statusCode}`);
            reject(new Error(`HTTP ${res.statusCode}: ${JSON.stringify(res.data)}`));
            return;
          }
          
          // 检查业务状态码
          if (res.data && typeof res.data === 'object') {
            // 如果返回的是标准格式 {code, message, data, success}
            if (res.data.hasOwnProperty('code') || res.data.hasOwnProperty('success')) {
              console.log('业务状态码:', res.data.code, '成功标识:', res.data.success);
              resolve(res.data);
            } else {
              // 如果返回的是直接数据，包装成标准格式
              console.log('包装直接数据为标准格式');
              resolve({
                code: 200,
                message: 'success',
                data: res.data,
                success: true
              });
            }
          } else {
            // 处理非对象响应
            console.log('包装非对象数据为标准格式');
            resolve({
              code: 200,
              message: 'success',
              data: res.data,
              success: true
            });
          }
        },
        fail: (err) => {
          console.error(`API请求失败: ${method.toUpperCase()} ${url}`, err);
          
          let errorMessage = '网络请求失败';
          let errorCode = -1;
          
          if (err.errMsg) {
            if (err.errMsg.includes('timeout')) {
              errorMessage = '请求超时，请稍后重试';
              errorCode = -2;
            } else if (err.errMsg.includes('fail')) {
              errorMessage = '网络连接失败，请检查网络';
              errorCode = -3;
            }
          }
          
          reject({
            code: errorCode,
            message: errorMessage,
            data: null,
            success: false,
            originalError: err
          });
        }
      };
      
      wx.request(requestOptions);
    });
  },

  /**
   * GET请求
   */
  get: function(url, params = {}) {
    const queryString = Object.keys(params)
      .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&');
    
    const fullUrl = queryString ? `${url}?${queryString}` : url;
    return this.request({ url: fullUrl, method: 'GET' });
  },

  /**
   * POST请求
   */
  post: function(url, data = {}) {
    return this.request({ url, method: 'POST', data });
  },

  /**
   * PUT请求
   */
  put: function(url, data = {}) {
    return this.request({ url, method: 'PUT', data });
  },

  /**
   * DELETE请求
   */
  delete: function(url, data = {}) {
    return this.request({ url, method: 'DELETE', data });
  },

  /**
   * 文件上传
   */
  upload: function(url, filePath, formData = {}) {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('token');
      const header = {};
      
      if (token) {
        header['Authorization'] = `Bearer ${token}`;
      }
      
      wx.uploadFile({
        url: this.baseURL + url,
        filePath: filePath,
        name: 'file',
        formData: formData,
        header: header,
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (e) {
            resolve(res.data);
          }
        },
        fail: (err) => {
          console.error('文件上传失败:', err);
          reject(err);
        }
      });
    });
  },

  /**
   * 微信登录
   */
  wechatLogin: function(code, userInfo) {
    return this.post('/api/user/wechat-login', {
      code,
      userInfo: JSON.stringify(userInfo) // 将userInfo对象序列化为JSON字符串
    });
  },

  /**
   * 获取用户信息
   */
  getUserInfo: function() {
    return this.get('/api/user/info');
  },

  /**
   * 更新用户信息
   */
  updateUserInfo: function(userInfo) {
    return this.put('/api/user/info', userInfo);
  },

  /**
   * 发送聊天消息
   */
  chat: function(data) {
    return this.post('/api/chat/send', data);
  },

  /**
   * 获取聊天历史
   */
  getChatHistory: function(params = {}) {
    const { page = 1, size = 20, type, functionCategory } = params;
    return this.get('/api/chat/history', { page, size, type, functionCategory });
  },

  /**
   * 删除聊天记录
   */
  deleteChatHistory: function(id) {
    return this.delete(`/api/chat/history/${id}`);
  },

  /**
   * 获取助理功能列表
   */
  getAssistantFunctions: function(category) {
    return this.get('/api/assistant/functions', { category });
  },

  /**
   * 获取助理功能分类
   */
  getAssistantCategories: function() {
    return this.get('/api/assistant/categories');
  },

  /**
   * 生成AI图片
   */
  generateImage: function(prompt, size = '1024x1024', options = {}) {
    const requestData = {
      prompt,
      size,
      model: options.model || 'doubao-seedream-4.0',
      // 🎨 默认启用组图功能
      sequential_image_generation: options.sequential_image_generation || "auto",
      sequential_image_generation_options: {
        max_images: options.max_images || 3
      }
    };
    
    // 如果有参考图，添加到请求参数中
    if (options.referenceImagePath) {
      requestData.referenceImagePath = options.referenceImagePath;
    }
    
    return this.post('/api/ai-image/generate', requestData);
  },

  /**
   * 获取AI图片生成历史
   */
  getImageHistory: function(params = {}) {
    const { page = 1, size = 20 } = params;
    return this.get('/api/ai-image/history', { page, size });
  },

  /**
   * 删除AI图片历史
   */
  deleteImageHistory: function(taskId) {
    return this.delete(`/api/ai-image/history/by-task/${taskId}`);
  },

  /**
   * 获取AI图片示例
   */
  getImageExamples: function(params = {}) {
    const { page = 1, size = 20, featured = false } = params;
    return this.get('/api/ai-image/examples', { page, size, featured });
  },

  /**
   * 获取示例详情聊天记录
   */
  getExampleChats: function(exampleId) {
    return this.get(`/api/ai-image/examples/${exampleId}/chats`);
  },

  /**
   * 上传用户作品
   */
  uploadExample: function(formData) {
    return this.post('/api/user-upload/example', formData);
  },

  /**
   * 上传用户作品（文件）
   */
  uploadExampleFile: function(filePath, formData) {
    return this.upload('/api/user-upload/example/file', filePath, formData);
  },

  /**
   * 获取VIP信息
   */
  getVipInfo: function() {
    return this.get('/api/vip/info');
  },

  /**
   * 获取VIP套餐
   */
  getVipPlans: function() {
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    console.log('调用VIP套餐API，时间戳:', timestamp);
    return this.get(`/api/vip/plans?_t=${timestamp}`);
  },

  /**
   * 创建VIP订单
   */
  createVipOrder: function(planId, paymentMethod) {
    return this.post('/api/vip/orders', {
      planId,
      paymentMethod
    });
  },

  /**
   * 获取用户统计
   */
  getUserStats: function() {
    return this.get('/api/personal/stats');
  },

  /**
   * 获取用户收藏
   */
  getUserFavorites: function(params = {}) {
    const { page = 1, size = 20, type } = params;
    const queryParams = { current: page, size };
    if (type && type !== 'all') {
      queryParams.type = type;
    }
    return this.get('/api/personal/favorites', queryParams);
  },

  /**
   * 添加收藏
   */
  addFavorite: function(type, contentId, title, content, imageUrl, contentData) {
    const params = {
      type,
      contentId,
      title
    };
    
    if (content) params.content = content;
    if (imageUrl) params.imageUrl = imageUrl;
    if (contentData) params.contentData = contentData;
    
    return this.post('/api/personal/favorites', params);
  },

  /**
   * 取消收藏 (根据收藏ID)
   */
  removeFavorite: function(favoriteId) {
    return this.delete(`/api/personal/favorites/${favoriteId}`);
  },

  /**
   * 取消收藏 (根据内容)
   */
  removeFavoriteByContent: function(contentType, contentId) {
    return this.delete(`/api/personal/favorites/content/${contentType}/${contentId}`);
  },

  /**
   * 获取用户任务
   */
  getUserTasks: function(params = {}) {
    const { page = 1, size = 20, status } = params;
    return this.get('/api/personal/tasks', { page, size, status });
  },

  /**
   * 完成用户任务
   */
  completeUserTask: function(taskId) {
    return this.post(`/api/personal/tasks/${taskId}/complete`);
  },

  /**
   * 获取钱包余额
   */
  getWalletBalance: function() {
    return this.get('/api/personal/wallet/balance');
  },

  /**
   * 获取钱包交易记录
   */
  getWalletTransactions: function(params = {}) {
    const { page = 1, size = 20 } = params;
    return this.get('/api/personal/wallet/transactions', { page, size });
  },

  /**
   * 获取VIP订单列表
   */
  getVipOrders: function(params = {}) {
    const { page = 1, size = 20 } = params;
    return this.get('/api/vip/orders', { page, size });
  },

  /**
   * 支付回调处理
   */
  handlePaymentCallback: function(orderNo, paymentData) {
    return this.post('/api/vip/payment/callback', {
      orderNo,
      paymentData
    });
  },

  // ==================== 积分系统相关API ====================
  
  /**
   * 获取用户积分信息
   */
  getCreditsInfo: function() {
    return this.get('/api/credits/info');
  },

  /**
   * 获取用户积分交易记录
   */
  getCreditsHistory: function(params = {}) {
    const { page = 1, size = 20 } = params;
    return this.get('/api/credits/history', { current: page, size });
  },

  /**
   * 获取积分套餐列表
   */
  getCreditsPackages: function() {
    return this.get('/api/credits/packages');
  },

  /**
   * 创建积分购买订单
   */
  createCreditsOrder: function(packageId, paymentMethod) {
    return this.post('/api/credits/orders', {
      packageId,
      paymentMethod
    });
  },

  /**
   * 积分购买支付回调处理
   */
  handleCreditsPaymentCallback: function(orderNo, paymentData) {
    return this.post('/api/credits/payment/callback', {
      orderNo,
      transactionId: paymentData.transactionId || paymentData.transaction_id
    });
  },

  /**
   * 获取积分消耗规则
   */
  getCreditsConsumptionRules: function() {
    return this.get('/api/credits/consumption/rules');
  },

  /**
   * 检查积分是否足够
   */
  checkCreditsEnough: function(amount) {
    return this.get('/api/credits/check', { amount });
  },

  // ==================== 开发测试API ====================
  
  /**
   * 开发测试：添加测试积分
   */
  addTestCredits: function(amount = 1000) {
    return this.request({
      url: `/api/credits/dev/add-test-credits?amount=${amount}`,
      method: 'POST'
    });
  },

  /**
   * 开发测试：重置积分
   */
  resetTestCredits: function(amount = 0) {
    return this.request({
      url: `/api/credits/dev/reset-credits?amount=${amount}`,
      method: 'POST'
    });
  }
};

// 导出API对象
module.exports = api;